from fastapi import FastAPI
from starlette.requests import Request
import os
from fastapi.templating import Jinja2Templates
from starlette.staticfiles import StaticFiles
from starlette.responses import RedirectResponse
from typing import List
from fastapi import FastAPI, File, UploadFile
from starlette.responses import HTMLResponse
import json
import uvicorn
import xxchinait
from tinydb import TinyDB, Query

location='static'

app = FastAPI()
app.mount('/static', StaticFiles(directory=location), name='static')
app.mount('/static0', StaticFiles(directory='static0'), name='static0') 



@app.get("/static")
def static0(item_id: str=None,q: str = ''):
    print('q:',q)
    #listfiles=os.listdir(location)
    def web(locationx):
        print('locationx:',locationx)
        if os.path.isfile(locationx):
            #return RedirectResponse(url=locationx)
            return '<dir><a href={}>{}</a></dir>'.format(locationx,locationx).replace('//','/')
        z=''
        
        for item in os.listdir(locationx):
            print(item,locationx+item)
            if os.path.isfile(locationx+'/'+item):
                print('isfile',locationx+'/'+item)
                z=z=z+'<dir><a href={}>{}</a></dir>'.format('/'+locationx+'/'+item,item)
            elif os.path.isdir(locationx+'/'+item):
                z=z=z+'<dir><a href={}>{}</a></dir>'.format('?q='+q+'/'+item,item)
        z=z.replace('//','/')
        return z

            
    title='''
    <div class="jumbotron">
      <h3>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{}</h3>
      '''

    return HTMLResponse(content=xxchinait.html.start+title.format(q)+web(location+'/'+q))

@app.get("/left")
def toplevel():
    #print('q:',q)
    #listfiles=os.listdir(location)
    location='static'
    z=''
    for item in os.listdir(location):
        if os.path.isdir(location+'/'+item):
            #z=z+'<dir><a href={} target="right1">{}</a></dir>'.format('static?q='+item,item)
            z=z+'<dir><li role="presentation"><a href={} target="right1">{}</a></li></dir>'.format('static?q='+item,item)
        
        

    

            

    z='<dir><a href=/jumbotron target="right1">知识库</a></dir>'+'<dir><a href={} target="right1">{}</a></dir>'.format('tree','知识树')\
       +'<dir><a href=/search target="right1">搜索</a></dir>'+z+'<dir><a href=/chromeoffice target="right1">office插件</a></dir><dir><a href=/forceupdate target="right1">强制更新</a></dir><dir><a href=/about target="right1">关于</a></dir>'
    return HTMLResponse(content=xxchinait.html.start+'<ul class="nav nav-pills">'+z+'</ul>')

#知识树，所有文档目录
@app.get("/tree")
def tree():
    location='static'
    def tree0(locationx):
        z=[]
        for root, dirs, files in os.walk(locationx, topdown=False):
            for name in files:
                z.append(os.path.join(root, name).replace('\\','/'))
            for name in dirs:
                z.append(os.path.join(root, name).replace('\\','/'))
        z.sort()
        return z
    z=''
    for item in tree0(location):
        item=item.replace('static','static?q=')
        z=z+'<dir><a href={}>{}</a></dir>'.format(item,item[10:])
        
    title='''
    <div class="jumbotron">
      <h2>&nbsp;&nbsp;&nbsp;&nbsp;    知识树</h2>
      <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  汇集所有文档目录，帮助您直达关键文档</p>
      '''
    return HTMLResponse(content=xxchinait.html.start+title+z)

@app.get("/search/")
def search0():

    
    
    return 'hello'

#搜索目录
@app.get("/search")
def search(q: str = None):
    inputa='''
    <h2>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;知识搜索</h2>
    <form class="form-inline" action="/search" method="get">
      <div class="form-group">
        
        <input  class="form-control" id=q placeholder={} name="q" style="width:500px">
      

      <button type="submit" class="btn btn-default">搜索</button>
      </div>
    </form>
        '''
    if q:
        def db_search(keyword):
            User = Query()
            db = TinyDB('knowledge.json')
            test_func = lambda s: keyword in s
            return db.search(User.content.test(test_func))
        z=''
        for item in db_search(q):
            #z=z+'<dir><a href={}>{}</a></dir>'.format(item['dirname']+'/'+item['basename'],item['basename'])+\
            #   '<div class="panel panel-success">  <div class="panel-body">{}  </div></div>'.format(item['content'])
            
            #z=z+'<p>'+item['dirname']+'/'+item['basename']+'</p>'
            z=z+'<div class="panel panel-info">  <div class="panel-heading">    <h3 class="panel-title">{}</h3> \
            </div>  <div class="panel-body">    {}  </div></div>'.format('<dir><a href={}>{}</a></dir>'.format(item['path0'],item['path0'][7:]),item['content'].replace(q,'<font size="2" color="red">{}</font>'.format(q)))
        return HTMLResponse(content=xxchinait.html.start+inputa.format(q)+z)
        return HTMLResponse(content=xxchinait.html.start+inputa.format(q)+str(db_search(q)))
    else:

        return HTMLResponse(content=xxchinait.html.start+inputa.format('关键词'))



#在线预览office的chrome插件
@app.get("/chromeoffice")
def chromeoffice():
    return HTMLResponse(content=xxchinait.html.start+'<dir>chrome地址栏中输入 chrome://extensions/ 选择加载已解压的扩展程序 把下面的路径复制粘贴过来 </dir><dir><a href="\\\\10.102.10.13\\tools\\100.tmp\\chrome\\office_google_chrome">chrome在线浏览office插件安装路径</a></dir>')


#更新文档的方式
@app.get("/update")
def treex():
    a='''
    <button type="button" class="btn btn-lg btn-info" data-toggle="popover" title="如何增改删文档?" data-content="\\\\bjg1filesv4p\\Knowledge_Base\\ 共享网盘式操作，简单方便">右键复制，到资源管理器打开</button>
 '''
    return HTMLResponse(content=xxchinait.html.start+'<dir>右键复制下面的链接， 使用资源管理器（点击开始，粘贴）\
打开</dir><dir><a href="\\\\bjg1filesv4p\\Knowledge_Base\\">\\\\bjg1filesv4p\\Knowledge_Base\\</a></dir>'+a+xxchinait.html.end)


#@app.get("/left")
#def left():
    #return RedirectResponse(url='/lists')
#    return HTMLResponse(content=xxchinait.html.left_page.format(xxchinait.html.head))


#默认主目录
@app.get("/")
def main():

    return HTMLResponse(content=xxchinait.html.index)





#默认右边显示
@app.get("/right")
def right():
    return RedirectResponse(url='/jumbotron')

    return HTMLResponse(content=xxchinait.html.start+'<a href="/search"><img src="/static0/images/a.jpg"  alt="上海鲜花港 - 郁金香" /></a>')

#巨幕
@app.get("/jumbotron")
def jumbotron():
    inputa='''
    <form class="form-inline" action="/search" method="get">
      <div class="form-group">
        
        <input  class="form-control" id=q placeholder={} name="q" style="width:500px">
      

      <button type="submit" class="btn btn-default">搜索</button>
      </div>
    </form>
        '''
    x='''
    <div class="jumbotron"> 
      <h2>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;欢迎进入XX中国IT知识库!</h2>
      <p>我们的知识库是为了沉淀工作中的知识，分享彼此的经验，计划未来将包含SAP，运维，开发等众多模块</p>
      <p>大家把docx,xlsx,pptx,pdf,txt等知识文件，共享出来， 聚沙成塔，由水滴汇成小溪，小溪汇成河流，河流汇成湖泊，湖泊聚成知识点的海洋</p>
      <form class="form-inline" action="/search" method="get">
      <div class="form-group">
        
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input  class="form-control" id=q placeholder="关键词" name="q" style="width:500px">
      

      <button type="submit" class="btn btn-primary btn-lg">搜索</button><a class="btn btn-default btn-lg" href="/update" role="button">更新</a>
      </div>
      </form>
      <a href="/search"><img src="/static0/images/a1.jpg"  alt="上海鲜花港 - 郁金香" /></a>
    </div>
    ''
    '''
    return HTMLResponse(content=xxchinait.html.start+x)

#默认主目录
@app.get("/about")
def about():

    return HTMLResponse(content=XXchinait.html.start+'<h4><p>软件架构采用python3作为语言，fastapi作为web框架，tinydb作为非关系型数据库</p></h4><p>有问题，找XX</p>')

#强制更新
@app.get("/forceupdate")
def forceupdate():
    os.system('cd /data && python3 database.py')

    return HTMLResponse(content=xxchinait.html.start+'<h4><p>已强制更新</p></h4>')

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0",port=8000,log_level="info")
